package com.dylan.历史.多线程.并发编程的艺术.编程基础.自制线程池;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by Dylan on 2018/7/17.
 *
 * 线程池的实现
 */
public class DefaultThreadPool<Job extends Runnable> implements ThreadPool<Job> {
    // 线程池最大限制数
    private static final int MAX_WORKER_NUMBERS      = 10;
    // 线程池默认的数量
    private static final int DEFAULT_WORKER_NUMBERS  = 5;
    // 线程池最小的数量
    private static final int MIN_WORKER_NUMBERS      = 1;

    // 任务列表
    private final LinkedList<Job> jobs = new LinkedList<>();
    // 工作者列表
    private final List<Worker> workers = Collections.synchronizedList(new ArrayList<>());
    // 工作者线程的数量
    private int workerNum = DEFAULT_WORKER_NUMBERS;

    // 线程编号生成
    private AtomicLong threadNum = new AtomicLong();

    public DefaultThreadPool() {
        this(DEFAULT_WORKER_NUMBERS);
    }

    public DefaultThreadPool(int num) {
        this.workerNum = Math.max(Math.min(num, MAX_WORKER_NUMBERS), MIN_WORKER_NUMBERS);
        initializeWorkers(workerNum);
    }

    @Override
    public void execute(Job job) {
        if (job != null) {
            // 添加一个任务,然后进行通知
            synchronized (jobs) {
                jobs.addLast(job);
                jobs.notify();
            }
        }

    }

    @Override
    public void shutdown() {
        for (Worker worker : workers) {
            worker.shutdown();
        }
    }

    @Override
    public synchronized void addWorkers(int num) {
        if (workerNum + num > MAX_WORKER_NUMBERS) {
            num = MAX_WORKER_NUMBERS - workerNum;
        }
        if (num > 0) {
            initializeWorkers(num);
        }
    }

    @Override
    public synchronized void removeWorker(int num) {
        if (num >= workerNum) {
            throw new IllegalArgumentException(num + " beyond workerNum " + workerNum);
        }
        // 停止指定数量的工作者
        int count = 0;
        while (count < num) {
            Worker worker = workers.get(0);
            if (workers.remove(worker)) {
                worker.shutdown();
                count++;
            }
        }
        workerNum -= count;
    }

    @Override
    public int getJobSize() {
        return jobs.size();
    }

    private void initializeWorkers(int num) {
        for (int i = 0; i < num; i++) {
            Worker worker = new Worker();
            workers.add(worker);
            Thread workerThread = new Thread(worker, "ThreadPool-Worker-" + threadNum.incrementAndGet());
            workerThread.start();
        }
    }

    class Worker implements Runnable {
        // 是否工作,其他线程会操作该变量,所以设置为volatile
        private volatile boolean running = true;

        @Override
        public void run() {
            while (running) {
                Job job = null;
                synchronized(jobs) {
                    // 如果任务列表为空,那么就wait
                    while (jobs.isEmpty()) {
                        try {
                            jobs.wait();
                        } catch (InterruptedException e) {
                            // 感知到外部对WorkerThread的中断操作,返回
                            Thread.currentThread().interrupt();
                            return;
                        }
                    }
                    // 取出一个任务
                    job = jobs.removeFirst();
                }
                if (job != null) {
                    try {
                        job.run();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        public void shutdown() {
            running = false;
        }
    }
}
